package com.yuwj.chinaa.activity;

import android.content.Context;
import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.yuwj.chinaa.R;
import com.yuwj.chinaa.adapter.GTETransactionRecordAdapter;
import com.yuwj.chinaa.base.BaseActivity;
import com.yuwj.chinaa.base.ConstantParam;
import com.yuwj.chinaa.entity.EntityAssetGTEDetail;
import com.yuwj.chinaa.entity.EntityAssetGTETransactionRecord;
import com.yuwj.chinaa.entity.EntityAssetGTKDetail;
import com.yuwj.chinaa.entity.EntityAssetGTKTransactionRecord;
import com.yuwj.chinaa.entity.EntityPage;
import com.yuwj.chinaa.presenter.IPresenter;
import com.yuwj.chinaa.presenter.presenterImpl.PresenterImpl;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class AssetWalletActivity extends BaseActivity {


    IPresenter presenter;
    EntityPage entityPage;
    boolean isRefresh = true;
    int accountType;
    String recordType = ConstantParam.ACCOUNT_TRANSFER_TYPE_ALL;
    final int REQ_CODE_WITH_TRANSFER = 1;
    EntityAssetGTEDetail entityAssetGTEDetail;
    EntityAssetGTKDetail entityAssetGTKDetail;
    GTETransactionRecordAdapter gteTransactionRecordAdapter;
    List<Object> GTERecordList;


    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_total)
    TextView tvTotal;
    @BindView(R.id.tv_total_unit)
    TextView tvTotalUnit;
    @BindView(R.id.tv_cny)
    TextView tvCny;
    @BindView(R.id.tv_available)
    TextView tvAvailable;
    @BindView(R.id.tv_freez)
    TextView tvFreez;
    @BindView(R.id.ll_base_info_container)
    LinearLayout llBaseInfoContainer;
    @BindView(R.id.ll_recharge)
    LinearLayout llRecharge;
    @BindView(R.id.ll_withdraw_deposit)
    LinearLayout llWithdrawDeposit;
    @BindView(R.id.ll_menu_container)
    LinearLayout llMenuContainer;
    @BindView(R.id.rv_trading_record)
    RecyclerView rvTradingRecord;
    @BindView(R.id.wrl_trading_record)
    SwipeRefreshLayout wrlTradingRecord;
    @BindView(R.id.detail_record_container)
    LinearLayout detailRecordContainer;
    @BindView(R.id.tv_another_account_type)
    TextView tvAnotherAccountType;
    @BindView(R.id.ll_another_account_type)
    LinearLayout llAnotherAccountType;
    @BindView(R.id.rl_back)
    RelativeLayout rlBack;
    @BindView(R.id.tl_record_type)
    TabLayout tlRecordType;


    public static Intent createIntent(Context context, int accountType) {
        Intent intent = new Intent(context, AssetWalletActivity.class);
        intent.putExtra("accountType", accountType);
        return intent;
    }

    @Override
    public int setCustomContentViewResourceId() {
        return R.layout.activity_wallet;
    }

    @Override
    public void initParam() {
        presenter = new PresenterImpl(this);
        GTERecordList = new ArrayList<>();
//        GTKRecordList = new ArrayList<>();
        accountType = getIntent().getIntExtra("accountType", ConstantParam.ACCOUNT_TYPE_WITH_GTE);
        entityPage = new EntityPage();
        entityPage.setPageNo(-1);//由于首页传0,我们在发送请求时都是发送下一页,所以此处初始化为-1
    }

    @Override
    public void initView() {
        tlRecordType.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                String type = tab.getText().toString();
                switch (type) {
                    case "全部记录":
                        recordType = ConstantParam.ACCOUNT_TRANSFER_TYPE_ALL;
                        refresh();
                        break;
                    case "充值记录":
                        recordType = ConstantParam.ACCOUNT_TRANSFER_TYPE_CHARGE;
                        refresh();
                        break;
                    case "提币记录":
                        recordType = ConstantParam.ACCOUNT_TRANSFER_TYPE_PULL;
                        refresh();
                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }

    @Override
    public void initOperator() {
        updateAssetDetail(accountType);
    }

    /**
     * 根据账户类型,更新界面
     *
     * @param assetAccountType 账户类型
     */
    public void updateAssetDetail(int assetAccountType) {
        switch (assetAccountType) {
            case ConstantParam.ACCOUNT_TYPE_WITH_GTE:
                JSONObject jsonObjWithAssetGTEDetailParam = new JSONObject();
                try {
                    jsonObjWithAssetGTEDetailParam.put("page", entityPage.getComputeNextPage() + "");
                    jsonObjWithAssetGTEDetailParam.put("pageSize", entityPage.getPageSize() + "");
                    jsonObjWithAssetGTEDetailParam.put("sourceType", recordType + "");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                presenter.assetGTEDetail(jsonObjWithAssetGTEDetailParam.toString());
                break;
            case ConstantParam.ACCOUNT_TYPE_WITH_GTK:
                JSONObject jsonObjWithAssetGTKDetailParam = new JSONObject();
                try {
                    jsonObjWithAssetGTKDetailParam.put("page", entityPage.getComputeNextPage() + "");
                    jsonObjWithAssetGTKDetailParam.put("pageSize", entityPage.getPageSize() + "");
                    jsonObjWithAssetGTKDetailParam.put("sourceType", recordType + "");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                presenter.assetGTKDetail(jsonObjWithAssetGTKDetailParam.toString());
                break;
        }
    }

    void refresh() {
        isRefresh = true;
        entityPage.setPageNo(-1);
        wrlTradingRecord.setRefreshing(false);
        updateAssetDetail(accountType);
    }

    void loadMore() {
        isRefresh = false;
        updateAssetDetail(accountType);
    }

    @OnClick({R.id.rl_back, R.id.ll_another_account_type, R.id.ll_recharge, R.id.ll_withdraw_deposit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_another_account_type:
                if (accountType == ConstantParam.ACCOUNT_TYPE_WITH_GTE) {
                    accountType = ConstantParam.ACCOUNT_TYPE_WITH_GTK;
                } else {
                    accountType = ConstantParam.ACCOUNT_TYPE_WITH_GTE;
                }
                entityPage.setPageNo(-1);
                isRefresh = true;
                updateAssetDetail(accountType);
                break;
            case R.id.rl_back:
                finish();
                break;
            case R.id.ll_recharge:
                startActivity(TransferRechargeActivity.createIntent(context, accountType));
                break;
            case R.id.ll_withdraw_deposit:
                startActivityForResult(TransferTransferActivity.createIntent(context, accountType), REQ_CODE_WITH_TRANSFER);
                break;
        }
    }


    private void updateGTEUI(EntityAssetGTEDetail entityAssetGTEDetail) {
        tvTitle.setText("GTE");
        tvAnotherAccountType.setText("GTK");
        tvTotal.setText(entityAssetGTEDetail.getTotalAmount());
        tvFreez.setText(entityAssetGTEDetail.getFreezeAmount());
        tvAvailable.setText(entityAssetGTEDetail.getAvailableAmount());
        List<EntityAssetGTETransactionRecord> recordList = entityAssetGTEDetail.getRecordList();
        wrlTradingRecord.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
        if (recordList != null) {
            if (gteTransactionRecordAdapter == null) {
                GTERecordList.clear();
                GTERecordList.addAll(recordList);
                gteTransactionRecordAdapter = new GTETransactionRecordAdapter(context, GTERecordList);
                rvTradingRecord.setAdapter(gteTransactionRecordAdapter);
                gteTransactionRecordAdapter.setEmptyView(R.layout.content_recyclerview_empty, (ViewGroup) rvTradingRecord.getParent());
                rvTradingRecord.setLayoutManager(new LinearLayoutManager(context));
                gteTransactionRecordAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                    @Override
                    public void onLoadMoreRequested() {
                        loadMore();
                    }
                }, rvTradingRecord);
            } else {
                if (isRefresh) {
                    GTERecordList.clear();
                }
                GTERecordList.addAll(entityAssetGTEDetail.getRecordList());
                gteTransactionRecordAdapter.notifyDataSetChanged();
            }
        }
    }

    private void updateGTKUI(EntityAssetGTKDetail entityAssetGTKDetail) {
        tvTitle.setText("GTK");
        tvAnotherAccountType.setText("GTE");
        tvTotal.setText(entityAssetGTKDetail.getTotalAmount());
        tvFreez.setText(entityAssetGTKDetail.getFreezeAmount());
        tvAvailable.setText(entityAssetGTKDetail.getAvailableAmount());
        List<EntityAssetGTKTransactionRecord> recordList = entityAssetGTKDetail.getRecordList();
        if (recordList != null) {
            if (gteTransactionRecordAdapter == null) {
                GTERecordList.clear();
                GTERecordList.addAll(recordList);
                gteTransactionRecordAdapter = new GTETransactionRecordAdapter(context, GTERecordList);
                rvTradingRecord.setAdapter(gteTransactionRecordAdapter);
                rvTradingRecord.setLayoutManager(new LinearLayoutManager(context));
                gteTransactionRecordAdapter.setEmptyView(R.layout.content_recyclerview_empty, (ViewGroup) rvTradingRecord.getParent());
                gteTransactionRecordAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                    @Override
                    public void onLoadMoreRequested() {
                        loadMore();
                    }
                });
            } else {
                if (isRefresh) {
                    GTERecordList.clear();
                }
                GTERecordList.addAll(entityAssetGTKDetail.getRecordList());
                gteTransactionRecordAdapter.notifyDataSetChanged();
            }
        }
    }


    @Override
    public void onAssetGTEDetailSuccess(EntityAssetGTEDetail entityAssetGTEDetail) {
        super.onAssetGTEDetailSuccess(entityAssetGTEDetail);
        this.entityAssetGTEDetail = entityAssetGTEDetail;
        updateGTEUI(entityAssetGTEDetail);
        List<EntityAssetGTETransactionRecord> recordList = entityAssetGTEDetail.getRecordList();
        entityPage.setPageNo(entityPage.getComputeNextPage());
        if (recordList != null) {
            if (recordList.size() < entityPage.getPageSize()) {
                gteTransactionRecordAdapter.loadMoreEnd();
            } else {
                gteTransactionRecordAdapter.loadMoreComplete();
            }
        }
    }


    @Override
    public void onAssetGTEDetailFail(Exception e) {
        super.onAssetGTEDetailFail(e);
        if (gteTransactionRecordAdapter != null) {
            gteTransactionRecordAdapter.loadMoreFail();
        }
    }


    @Override
    public void onAssetGTKDetailSuccess(EntityAssetGTKDetail entityAssetGTKDetail) {
        super.onAssetGTKDetailSuccess(entityAssetGTKDetail);
        this.entityAssetGTKDetail = entityAssetGTKDetail;
        updateGTKUI(entityAssetGTKDetail);
        List<EntityAssetGTKTransactionRecord> recordList = entityAssetGTKDetail.getRecordList();
        entityPage.setPageNo(entityPage.getComputeNextPage());
        if (recordList != null) {
            if (recordList.size() < entityPage.getPageSize()) {
                gteTransactionRecordAdapter.loadMoreEnd();
            } else {
                gteTransactionRecordAdapter.loadMoreComplete();
            }
        }
    }


    @Override
    public void onAssetGTKDetailFail(Exception e) {
        super.onAssetGTKDetailFail(e);
        if (gteTransactionRecordAdapter != null) {
            gteTransactionRecordAdapter.loadMoreFail();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQ_CODE_WITH_TRANSFER) {
            entityPage.setPageNo(-1);
            isRefresh = true;
            updateAssetDetail(accountType);
        }
    }

}
